<?php
/**
 * Created by PhpStorm.
 * User: 小灰灰
 * Date: 2023-10-12
 * Time: 14:54:47
 * Info:
 */

namespace plugin\huiblog\app\model;

use support\Cache;
use think\Model;
use think\facade\Db;

class Keywords extends Model
{

    protected $table = 'blog_keywords';

    /**
     * 文章关键词关联操作
     */
    public function articleKeywordsEdit($articleId, $keywordNames = [])
    {
        Db::table('blog_article_keywords')->where(['aid' => $articleId])->delete();
        $keywordArray = explode(',', $keywordNames);
        $res_keyword  = $this->insertKeyword($keywordArray, $articleId);
    }

    public function insertKeyword($keywordArray = [], $aid = 0)
    {
        $insert = [];
        $time   = time();
        foreach ($keywordArray as $key => $value) {
            if ( ! $value) {
                continue;
            }
            $keywords_id = $this->increase($value);
            $insert[]    = [
                'aid'         => $aid,
                'keywords_id' => $keywords_id,
                'create_time' => $time,
            ];
        }
        $res = Db::table('blog_article_keywords')->strict(false)->field(true)->insertAll($insert);

        return $res;
    }

    //删除关键词
    public function deleteKeyword($keywordsId)
    {
        $res = Db::table('blog_article_keywords')->where('keywords_id', $keywordsId)->delete();

        return $res;
    }

    // 关联关键字
    public function increase($keywords)
    {
        $is_exist = $this->where('title', $keywords)->find();
        if ($is_exist) {
            $res = $is_exist['id'];
        } else {
            $res = $this->strict(false)->field(true)->insertGetId(['title' => $keywords, 'create_time' => time()]);
        }

        return $res;
    }

    // 获取tag列表
    public function tags($limit = 10, $order = '')
    {
        $map   = [];
        $map[] = ['status', '=', 1];
        $sort  = 'id desc';
        if ($order != '') {
            $sort = $order;
        }
        if ($order == 'rand()') {
            $tags = Keywords::where($map)->orderRaw("rand()")->limit($limit)->select()->toArray();
        } else {
            $tags = Keywords::where($map)->order($sort)->limit($limit)->select()->toArray();
        }
        foreach ($tags as $key => $v) {
            $tags[$key]['url'] = "/blog/lists?tag_id=".$v['id'];
        }

        return $tags;
    }

    // 获取搜索关键字列表
    public function search_key($limit = 10, $is_rand = 0, $order = '')
    {
        return [];
    }

    /**
     * 获取关键词总数
     * @return void
     */
    public function count()
    {
        if (Cache::get('blogKeywordsCount')) {
            $count = Cache::get('blogKeywordsCount');
        } else {
            $count = Keywords::where(['delete_time' => 0])->count();
            Cache::set('blogKeywordsCount', $count);
        }

        return $count;
    }

}
